#include "message_router.hpp"
#include "../utils/logger.hpp"
#include "server.hpp"

MessageRouter& MessageRouter::getInstance() {
    static MessageRouter instance;
    return instance;
}

void MessageRouter::registerHandler(std::shared_ptr<MessageHandler> handler) {
    std::lock_guard<std::mutex> lock(handlers_mutex_);
    handlers_[handler->getType()] = handler;
}

void MessageRouter::route(struct lws *wsi, const std::string& message) {
    try {
        // 解析消息
        auto json = nlohmann::json::parse(message);
        std::string type = json["type"];

        // 查找处理器
        std::shared_ptr<MessageHandler> handler;
        {
            std::lock_guard<std::mutex> lock(handlers_mutex_);
            auto it = handlers_.find(type);
            if (it != handlers_.end()) {
                handler = it->second;
            }
        }

        if (handler) {
            // 调用处理器
            handler->handle(wsi, json["data"]);
        } else {
            // 未知消息类型
            Logger::getInstance().warn("Unknown message type: {}", type);
            
            nlohmann::json response = {
                {"type", "error"},
                {"data", {
                    {"message", "Unknown message type"}
                }}
            };
            Server::getInstance().sendMessage(wsi, response.dump());
        }
    } catch (const std::exception& e) {
        // JSON解析错误或其他异常
        Logger::getInstance().error("Failed to route message: {}", e.what());
        nlohmann::json response = {
            {"type", "error"},
            {"data", {
                {"message", "Invalid message format"}
            }}
        };
        Server::getInstance().sendMessage(wsi, response.dump());
    }
} 